import React from 'react'
import {withRouter} from 'react-router-dom'
import {connect,} from 'react-redux'
// icon
import MarkIcon from '../../res/images/web/game/shoucang@2x.png'
import MarkedIcon from '../../res/images/web/game/shoucang_selected@2x.png'
import SmallPlayBtn from '../../res/images/web/shared/small-triangle.png'
import YellowBtn from '../../res/images/web/FootballGameCard/btn／in yellow@2x.png'
// constants
// antd-mobile
import {Icon, WingBlank,} from "antd-mobile"

// utils
import './FootballGameCard.css'
import {getDifferenceBetweenDates, formatScheduleDate, formatDate, getWeekDayFromDateString} from "../../utils/dateService";
import LocalStorageService from "../../utils/LocalStorageService";
import {isEmptyObject} from "rc-form/lib/utils";
import {formatAsiaOdd} from "../../containers/game-room/components/Main/index/AsiaOddsTable/AsiaOddsTable";
import {formatDXQOdd} from "../../containers/game-room/components/Main/index/BigSmallTable/BigSmallTable";
import {behaviorReq} from "../../apis/goApis";
import constants from "../../utils/constants";
import TeamAvatar from "../../containers/game-room/components/Header/Versus/TeamAvatar/TeamAvatar";
import zhuSrc from '../../res/images/web/FootballGameCard/主红@2x.png'
import keSrc from '../../res/images/web/FootballGameCard/客蓝@2x.png'

const FootballGameCard = props => {

    const {
        game,
        history,
        search,
    } = props

    if (game === null || isEmptyObject(game)) return null

    const {
        matchId,
        eventId,
        status,
        schedule,
        startAt,
        homeTeam,
        awayTeam,
        gameInfo,
        seasonInfo,
        stageInfo,
        event,
        stage,
        gameIndex,
    } = game



    // 比赛状态判断条件
    let isMarked = false
    const dateString = formatDate(new Date(schedule * 1000))
    const login = LocalStorageService.get('isLogin')
    if (login) {
        const ls = LocalStorageService.get('follow_games')
        if (ls) {
            const markList = LocalStorageService.get('follow_games')[dateString]
            if (markList) {
                isMarked = markList.findIndex(game => game.matchId === matchId) > -1
            }
        }
    }

    const isEarly = status === 1
    const isStarted = status >= 2 || status <= 7
    const isFirstHalf = status === 2
    const isHalfTime = status === 3
    const isSecondHalf = status === 4
    const isJiashi = status === 5
    const isFinished = status === 8
    const isDelay = status >= 9

    const startAtTimeObj = new Date(startAt * 1000)
    const now = new Date()
    const diff = getDifferenceBetweenDates(startAtTimeObj, now)

    const cTimeStyle = {
        color: !isEarly  ? `#FFA500` : '#ddd',
    }
    const competitionName = event && event.short_name_zh ? event.short_name_zh : ''
    let date = formatDate(new Date(schedule * 1000))
    let scheduleTime = formatScheduleDate(new Date(schedule * 1000))
    let weekday = getWeekDayFromDateString(new Date(schedule * 1000))

    let pushDateString = formatDate(new Date(schedule * 1000))
    // console.log(pushDateString)
    let curTime
    if (isEarly) curTime = '未'
    if (isFirstHalf) curTime = <>{diff.minutesDiff + 1}<span className='second-blink'>'</span></>
    // if (isHalfTime) curTime = <>半场 45<span className='second-blink'>'</span></>
    if (isHalfTime) curTime = <>中</>
    if (isSecondHalf) curTime = <>{diff.minutesDiff + 45 + 1}<span className='second-blink'>'</span></>
    if (isJiashi) curTime = <>90+<span className='second-blink'>'</span></>
    if (isFinished) curTime = <>完</>

    const infoOffer = seasonInfo ? seasonInfo[3] === 1 : false
    const lives = props.gameState.lives
    let isVodLive = false
    if (lives.length > 0 && lives.find(live => live.id === matchId)) {
        isVodLive = true
    }
    const infoIcon = <div className='game-football-game-item-header-info'>
        <span className='game-football-game-item-header-info-span'>情报</span>
    </div>
    const liveIcon = <div className='game-football-game-item-header-info game-football-game-item-header-info-live'>
        <span className='game-football-game-item-header-info-span'>视频</span>
    </div>
    const markedIcon = <div
        className='game-football-game-item-header-mark'
    >
        <img src={MarkedIcon} alt=''/>
    </div>
    const unmarkedIcon = <div
        className='game-football-game-item-header-mark'
    >
        <img src={MarkIcon} alt=''/>
    </div>


    let icons = <div className='game-football-game-item-header-icons'>
        {login && infoOffer ? infoIcon : null}
        {isVodLive ? liveIcon : null}
        {isMarked ? markedIcon : unmarkedIcon}
    </div>

    const headerTemplate = (
        <div className='game-football-game-item-header'>
            <div className='game-football-game-item-header-category'>{competitionName}</div>
            <div className='game-football-game-item-header-sa'>{isDelay ? '' : scheduleTime}</div>
            {isDelay ?
                <div className='game-football-game-item-header-delay'>推迟</div>
                : <div
                    className='game-football-game-item-header-ct'
                    style={{
                        color: isStarted && !isFinished ? '#FFA500' : '#333',
                    }}
                >{curTime}</div>
            }
            {isFinished ? null : icons}
        </div>

    )

    // players templatecon
    // console.log(homeTeam)
    const homeTeamDetail = homeTeam.detail
    const awayTeamDetail = awayTeam.detail
    if (homeTeamDetail === undefined || awayTeamDetail === undefined) return null
    const homeTeamName = homeTeamDetail.name_zh
    const homeScore = homeTeam.teamScore
    const homeScoreHalf = homeTeam.teamScoreHalf
    const awayScoreHalf = awayTeam.teamScoreHalf
    const awayTeamName = awayTeamDetail.name_zh
    const awayScore = awayTeam.teamScore
    const homeRedCard = homeTeam.red
    const homeYellowCard = homeTeam.yellow
    const awayRedCard = awayTeam.red
    const awayYellowCard = awayTeam.yellow

    const scoreTemplate = `${homeScore}:${awayScore}`
    const VSTemplate = `-`
    const cardTemplate = (color, number) => {
        const cardStyle = {
            display: 'inline-block',
            width: '14px',
            height: '16px',
            minWidth: '14px',
            minHeight: '16px',
            backgroundColor: color === 'yellow' ? 'rgba(255,165,0,1)' : 'rgba(255,57,36,1)',
            color: '#fff',
            marginLeft: '2px',
            textAlign: 'center',
            fontSize: '12px',
            paddingBottom: '2px',
        }
        return <div style={cardStyle}>{number}</div>
    }

    const player = (player, home) => {
        const cards = <>
            {player.yellow ? cardTemplate('yellow', player.yellow) : null}
            {player.red ? cardTemplate('red', player.red) : null}
        </>
        const avatar = <TeamAvatar
            iconUrl={player.logo || (home ? zhuSrc : keSrc)}
            noPrefix={player.logo.length === 0}
        />
        const template = (
            <div className='game-football-game-item-player-ctn'>
                {home ? cards : null}
                {home ? null : avatar}
                <span
                    style={{
                        fontWeight: 'bold',
                        textAlign: home ? 'right' : 'left',
                        width: '100%',
                        margin: home ? '0 16px 0 0' : '0 0 0 16px',
                    }}
                >{player.name}</span>
                {!home ? null : avatar}
                {!home ? cards : null}
            </div>
        )
        return template
    }

    const p1 = {
        name: homeTeamName,
        red: homeRedCard,
        yellow: homeYellowCard,
        logo: homeTeamDetail.logo,
    }

    const p2 = {
        name: awayTeamName,
        red: awayRedCard,
        yellow: awayYellowCard,
        logo: awayTeamDetail.logo,

    }

    const playerTemplate = (
        <div className='flex-center-align-center game-football-game-item-vs-ctn'>
            {player(p1, true,)}
            <div className={`game-football-game-item-vs ${!isEarly ? 'game-football-game-item-vs-on-live' : ''}`}>
                {isEarly || isDelay ? VSTemplate : scoreTemplate}
            </div>
            {player(p2, false)}
        </div>
    )

    // footer template

    const homeTeamCorner = homeTeam.corner
    const awayTeamCorner = awayTeam.corner
    const homeTeamPenalty = homeTeam.penalty
    const awayTeamPenalty = awayTeam.penalty

    const isPenalty = homeTeamPenalty > 0 || awayTeamPenalty > 0



    const statsTemplate = (
        <div className='game-football-game-item-stat'>
            <span>半:{homeScoreHalf}-{awayScoreHalf}</span>
            <span>角:{homeTeamCorner <= 0 ? 0 : homeTeamCorner}-{awayTeamCorner <= 0 ? 0 : awayTeamCorner}</span>
            {isPenalty ? <span>点:{homeTeamPenalty}-{awayTeamPenalty}</span> : null}
        </div>
    )

    // const footerTemplate = (
    //     <div className='game-football-game-item-footer'>
    //         {/*<span>{weekday} {Number(gameIndex) + 1}</span>*/}
    //         {!isEarly ? statsTemplate : <div style={{height: '14px',}}/>}
    //     </div>
    // )


    const AIBtn = <div
        className='game-football-game-item-ai-btn'
        id='ai'
        onClick={(e) => goToGame(e)}
    >
        <img src={YellowBtn} alt=''/>
        {/*<img alt='' src={AIIcon} id='ai'/>*/}
        <span id='ai'>小应分析</span>
    </div>

    let addMsg = ''
    if (stage) {
        // console.log('stage', stage)
        const {
            round_count,
            group_count,
            mode,
            name_zh,
        } = stage

        if (mode) {
            const text = mode === 1 ? '积分赛-' : '淘汰赛-'
            addMsg += text
        }

        if (group_count > 0) {
            addMsg += `第${group_count}组-`
        }

        if (round_count > 0) {
            addMsg += `第${round_count}轮-`
        }

        addMsg += name_zh
    }
    const addMsgTemplate = (
        <div className='game-football-game-item-add'>
            {addMsg}
        </div>
    )

    const oddsList = props.gameState.odds[dateString]
    const oddsDate = oddsList && oddsList.find(o => o.id === matchId)
    let oddSTemplate = null

    if (oddsDate) {
        let r = oddsDate.r
        let d = oddsDate.d
        let rT = null
        let dT = null
        if (r) {
            rT = <span>{formatAsiaOdd(r[1])}</span>
        }
        if (d) {
            dT = <span>{formatDXQOdd(d[1])}球</span>
        }
        oddSTemplate = <div className='game-football-game-item-odds'>
            {rT}
            {dT}
        </div>
    }

    const mainTemplate = (
        // <div className='flex-space-between flex-column game-football-game-item'>
        <div className='game-football-game-item'>
            {headerTemplate}
            {playerTemplate}
            {/*{addMsg ? addMsgTemplate : null}*/}
            {statsTemplate}
            {/*{oddSTemplate}*/}
            {/*{search ? null : AIBtn}*/}
        </div>
    )

    // additional  message template




    return (
        <div
            onClick={(e) => goToGame(e)}
            style={{
                position: 'relative',
            }}
        >
            {mainTemplate}
        </div>
    )

    function goToGame(e) {
        const isLogin = LocalStorageService.get('userid')
        if (isLogin) {
            behaviorReq({
                userid: LocalStorageService.get('userid'),
                handle: '点击足球比赛',
            })
        }
        e.stopPropagation()
        let AIBtnClick = false
        if (e.target.id === 'ai') {
            AIBtnClick = true
        }
        history.push(`./game/${matchId}`, {matchId, status, AIBtnClick, date,})
    }
}

const mapState = state => ({
    gameState: state.game,
})

const mapDispatch = dispatch => ({
    doMarkGame: (payload) => dispatch.game.doMarkGame(payload),
})


export default connect(mapState, mapDispatch)(withRouter(FootballGameCard))
